import dayjs from 'dayjs'
import Schema from 'validate'
const formSchema = new Schema({
  houseId: {
    type: String,
    required: true,
    message: '请选择房屋~'
  },
  name: {
    type: String,
    required: true,
    message: '请填写访客姓名~'
  },
  gender: {
    type: Number,
    required: true,
    message: '请选择性别~'
  },
  mobile: {
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不正确~'
  },
  visitDate: {
    type: String,
    required: true,
    message: '请选择访问日期~'
  },
})

Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseId: '',
    houseInfo: '',
    name: '坤坤',
    gender: 1,
    mobile: '15915876390',
    // 当前时间绑定，时间戳
    currentDate: +dayjs(),
    // 选中时间绑定，YYYY-MM-DD
    visitDate: '',
    minDate: +dayjs(),
    maxDate: +dayjs().add(3, 'd')
  },
  async onLoad() {
    const res = await wx.http({ url: '/house' })
    this.setData({ houseList: res.data })
  },
  // 选中房屋事件
  onSelect(e) {
    // console.log('e -----> ', e);
    const { id, name } = e.detail
    this.setData({
      houseId: id,
      houseInfo: name
    })
  },
  // 选中日期的事件
  onSelectDate(e) {
    console.log('e -----> ', e);
    this.setData({
      currentDate: e.detail,
      visitDate: dayjs(e.detail).format('YYYY-MM-DD'),
      dateLayerVisible: false
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    const {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    } = this.data
    const data = {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    }
    const errors = formSchema.validate(data)
    if (errors.length) {
      return wx.utils.toast(errors[0].message)
    }
    await wx.http({ url: '/visitor', method: 'POST', data })
    wx.utils.toast('新增成功')
    setTimeout(() => {
      wx.navigateTo({
        url: '/visitor_pkg/pages/passport/index',
      })
    }, 1500);
  },
})
